package com.poisonh.unifiedauth.ui.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.model.WeekDataModel;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.GsonUtils;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

//import com.github.mikephil.charting.formatter.AxisValueFormatter;

/**
 * 折线图
 * Created by PoisonH on 2016/7/4.
 */
public class LineGraphFragment extends BaseFragment
{
    private LineChart mLineChart;
    private List<WeekDataModel> mList;
    private int average;
    YAxis axisLeft;
    XAxis xaxis;

//    @Override
//    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
//    {
//        @SuppressLint("InflateParams")
//        View view = inflater.inflate(R.layout.fragment_linegraph, null);
//        return view;
//    }

    @Override
    protected View loadView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.fragment_linegraph, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        mLineChart = (LineChart) view.findViewById(R.id.lcv_linegraph);

        initView();
        getAppLoginOther();
    }

    private void initView()
    {
        xaxis = mLineChart.getXAxis();
        xaxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//
//
//        YAxis axisRight = mLineChart.getAxisRight();
//        axisRight.setEnabled(false);
//
//
        axisLeft = mLineChart.getAxisLeft();


        //是否在折线图上添加边框
        mLineChart.setDrawBorders(false);

        // 数据描述
//        mLineChart.setDescription("");
        // 如果没有数据的时候，会显示这个，类似listview的emtpyview
//        mLineChart.setNoDataTextDescription("You need to provide data for the chart.");

        // 是否显示表格颜色
        mLineChart.setDrawGridBackground(false);
        // 表格的的颜色，在这里是是给颜色设置一个透明度
        mLineChart.setGridBackgroundColor(Color.WHITE & 0x70FFFFFF);

        // enable touch gestures
        // 设置是否可以触摸
        mLineChart.setTouchEnabled(false);

        // enable scaling and dragging
        // 是否可以拖拽
        mLineChart.setDragEnabled(false);
        // 是否可以缩放
        mLineChart.setScaleEnabled(false);

        // if disabled, scaling can be done on x- and y-axis separately
        mLineChart.setPinchZoom(false);//
        //x轴位置
        mLineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);

        YAxis axisRight = mLineChart.getAxisRight();
        axisRight.setEnabled(false);
        axisRight.setStartAtZero(true);

        axisLeft.setStartAtZero(true);
//        axisLeft.setLabelCount(5, true);
        axisLeft.setAxisMaxValue(5);
        axisLeft.setTextColor(Color.WHITE);
//        axisLeft.setAxisMinValue(0f);


        //   xaxis.setLabelCount(7, true);
        xaxis.setAxisMinValue(0f);
        xaxis.setTextColor(Color.WHITE);
        // xaxis.setAxisMaxValue(7);

        mLineChart.setDrawGridBackground(false);
        mLineChart.setEnabled(false);
        mLineChart.setScaleEnabled(false);
//        mLineChart.setDescription("");
    }


    /**
     * 获取数据
     */
    private void getAppLoginOther()
    {
        HttpParams params = new HttpParams();
        //  String mStrUserId = PreferencesUtils.getString(getActivity(), "ID");
        params.put("id", mStrUserId);
        //  params.put("id", ConstantUitls.mStrId);
        params.put("token", mStrUserToken);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.GETAPPLOGINOTHER, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                mList = new ArrayList<>();
                mList = GsonUtils.parseWeekData(response);
                Message message = Message.obtain();
                message.obj = mList;
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(String failReason)
            {
                ToastUtils.showToast(getContext(), "数据请求失败");
            }
        });
    }

    Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            loadData((List<WeekDataModel>) msg.obj);
        }
    };

    private void loadData(final List<WeekDataModel> mList)
    {
        int max = 0;
        if (mList.size() <= 0)
        {
            ToastUtils.showToast(getActivity(), "没有数据");
            return;
        }
        for (int i = 0; i < mList.size(); i++)
        {
            if (max < Integer.parseInt(mList.get(i).getVALUE()))
            {
                max = Integer.parseInt(mList.get(i).getVALUE());
            }
        }
        if (max < 5)
        {
            max = 5;
        }
        average = CalculatedAverage(max);

/*        axisLeft.setValueFormatter(new AxisValueFormatter()
        {
            @Override
            public String getFormattedValue(float value, AxisBase axis)
            {
                axis.setLabelCount(5);
                return (int) value * average + "";
            }

            @Override
            public int getDecimalDigits()
            {
                return 0;
            }

        });
        xaxis.setValueFormatter(new AxisValueFormatter()
        {
            @Override
            public String getFormattedValue(float value, AxisBase axis)
            {
                return mList.get((int) value).getWEEK();
            }

            @Override
            public int getDecimalDigits()
            {
                return 0;
            }
        });*/

        List<Entry> mListEntry = new ArrayList<>();
        Entry mEntry;
        for (int i = 0; i < mList.size(); i++)
        {
            mEntry = new Entry(i, CalculatedHeight(Integer.parseInt(mList.get(i).getVALUE())));
            //mEntry = new Entry(i, (Integer.parseInt(mList.get(i).getVALUE())));
            mListEntry.add(mEntry);
        }


        LineDataSet mLineDataSet = new LineDataSet(mListEntry, "PoisonH");
        LineData mLineData = new LineData(mLineDataSet);
        mLineData.setDrawValues(false);
        mLineChart.setData(mLineData);
    }

    /**
     * 计算平均值,向上取整
     *
     * @return
     */
    public int CalculatedAverage(int max)
    {
        return (int) (Math.ceil(max / 5f));
    }

    /**
     * 计算平均值,向上取整
     *
     * @return
     */
    public float CalculatedHeight(float val)
    {
        return val / average;
    }

}
